package com.yuma.communication;

class MyNumber{
    public static int number = 0;

    public synchronized void incr(){
        while(number != 0){
            // 让当前线程等待
            try {
                System.out.println(Thread.currentThread().getName()+" :进入等待池");
                wait();  // 等待，在哪等待在哪被唤醒
                System.out.println(Thread.currentThread().getName() +":从等待池被唤醒");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        number++;
        notifyAll();  // 随机唤醒
        System.out.println("自增：" +Thread.currentThread().getName()+" : "+number);
    }

    public synchronized void decr(){
        while (number != 1){
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        number--;
        notifyAll();  // 随机唤醒
        System.out.println("自减:" + Thread.currentThread().getName()+" : "+number);
    }
}


public class WaitNotifyDemo {
    public static void main(String[] args) {
        MyNumber myNumber = new MyNumber();

        for(int i = 0; i < 5; i++) {
            new Thread(() -> {
                myNumber.incr();
            }, String.valueOf(i)).start();
        }

        for(int i = 0; i < 5; i++) {
            new Thread(() -> {
                myNumber.decr();
            }, String.valueOf(i)).start();
        }
    }
}
